// $URL: http://mingw-lib.googlecode.com/svn/trunk/working/avcodec_to_widget_10/t_box_bar.cpp $
// $Rev: 322 $
// $Author: akio.miyoshi $
// $Date:: 2010-07-31 14:55:07 +0000#$

#include "t_box_bar.h"
#include "t_box_player_ctx.h"

QString T_VideoProgressBar::text() const
{
    QTime v_val_clock(0, 0, 0, 0);
    v_val_clock = v_val_clock.addMSecs(this->value());
    QTime v_max_clock(0, 0, 0, 0);
    v_max_clock = v_max_clock.addMSecs(this->maximum());
    return v_val_clock.toString("hh:mm:ss[zzz]") + "/" + v_max_clock.toString("hh:mm:ss[zzz]");
}

void T_VideoProgressBar::setElapsed(int a_msec)
{
    this->setValue(a_msec);
}

bool T_VideoProgressBar::event(QEvent *e)
{
    if(e->type()==QEvent::MouseButtonPress)
    {
        QMouseEvent *v_me = static_cast<QMouseEvent *>(e);
        Qt::MouseButtons v_buttons = v_me->buttons();
        if(! (v_buttons & Qt::LeftButton) )
        {
            return QProgressBar::event(e);
        }
        p_handle_seek_click(v_me);
        return QProgressBar::event(e);
    }
    if(e->type()==QEvent::MouseButtonRelease)
    {
        QMouseEvent *v_me = static_cast<QMouseEvent *>(e);
        Qt::MouseButtons v_buttons = v_me->buttons();
        if(! (v_buttons & Qt::LeftButton) ) return true;
        if(m_old_x >= 0 && qAbs(v_me->x()-m_old_x)<2)
        {
            return QProgressBar::event(e);
        }
        p_handle_seek_click(v_me);
        return QProgressBar::event(e);
    }
    if(e->type()==QEvent::MouseMove)
    {
        QMouseEvent *v_me = static_cast<QMouseEvent *>(e);
        Qt::MouseButtons v_buttons = v_me->buttons();
        if(! (v_buttons & Qt::LeftButton) ) return true;
        if(m_move_sw.elapsed()==0)
        {
            return QProgressBar::event(e);
        }
        int v_dist = qAbs(v_me->x()-m_old_x);
        double v_speed = 1.0 * v_dist / m_move_sw.elapsed();
        double v_speed_limit = v_speed * 40;
        if(v_speed_limit<5)
        {
            v_speed_limit = 5;
        }
        if(v_speed_limit>10)
        {
            v_speed_limit = 10;
        }
        if(m_old_x >= 0 && v_dist<v_speed_limit)
        {
            return QProgressBar::event(e);
        }
        m_move_sw.reset();
        p_handle_seek_click(v_me);
        return QProgressBar::event(e);
    }
    return QProgressBar::event(e);
}

void T_VideoProgressBar::p_handle_seek_click(QMouseEvent *v_me)
{
    int v_timing = p_calc_seek_timing(v_me);
    m_seek_manager->enqueueRequest(v_timing);
    emit clicked(v_timing);
}

int T_VideoProgressBar::p_calc_seek_timing(QMouseEvent *v_me)
{
    int x = v_me->x();
    m_old_x = x;
    int w = this->width();
    int v_min = this->minimum();
    int v_max = this->maximum();
    int v_one = v_max - v_min;
    qint64 value = v_min + (v_one * x / w);
    return (int)value;
}
